added samples
[windows-sources.git] / sdk / samples / all in on code / Visual Studio 2008 / CSFileMappingServer / Program.cs
blob630531f45226e857f56e79c8029907e0ace1a87a
1 /******************************** Module Header ********************************\
2 * Module Name: Program.cs
3 * Project: CSFileMappingServer
4 * Copyright (c) Microsoft Corporation.
5 *
6 * File mapping is a mechanism for one-way or duplex inter-process communication
7 * among two or more processes in the local machine. To share a file or memory,
8 * all of the processes must use the name or the handle of the same file mapping
9 * object.
11 * To share a file, the first process creates or opens a file by using the
12 * CreateFile function. Next, it creates a file mapping object by using the
13 * CreateFileMapping function, specifying the file handle and a name for the file
14 * mapping object. The names of event, semaphore, mutex, waitable timer, job, and
15 * file mapping objects share the same name space. Therefore the CreateFileMapping
16 * and OpenFileMapping functions fail if they specify a name that is in use by an
17 * object of another type.
19 * To share memory that is not associated with a file, a process must use the
20 * CreateFileMapping function and specify INVALID_HANDLE_VALUE as the hFile
21 * parameter instead of an existing file handle. The corresponding file mapping
22 * object accesses memory backed by the system paging file. You must specify a
23 * size greater than zero when you use an hFile of INVALID_HANDLE_VALUE in a call
24 * to CreateFileMapping.
26 * Processes that share files or memory must create file views by using the
27 * MapViewOfFile or MapViewOfFileEx function. They must coordinate their access
28 * using semaphores, mutexes, events, or some other mutual exclusion technique.
30 * The VC# code sample demonstrates creating a file mapping object named
31 * "Local\SampleMap" and writing a string to the file mapping. Because the Base
32 * Class Library of .NET Framework 2/3/3.5 does not have any public classes to
33 * operate on file mapping objects, you have to P/Invoke the Windows APIs as shown
34 * in this code sample.
36 * This source is subject to the Microsoft Public License.
37 * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
38 * All other rights reserved.
40 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
41 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
42 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
43 \*******************************************************************************/
45 #region Using directives
46 using System;
47 using System.Text;
48 using System.Runtime.InteropServices;
49 using System.Security;
50 using System.Runtime.ConstrainedExecution;
51 using System.Security.Permissions;
52 using Microsoft.Win32.SafeHandles;
53 using System.ComponentModel;
54 #endregion
57 namespace CSFileMappingServer
59 class Program
61 // In terminal services: The name can have a "Global\" or "Local\"
62 // prefix to explicitly create the object in the global or session
63 // namespace. The remainder of the name can contain any character except
64 // the backslash character (\). For more information, see:
65 // http://msdn.microsoft.com/en-us/library/aa366537.aspx
66 internal const string MapPrefix = "Local\\";
67 internal const string MapName = "SampleMap";
68 internal const string FullMapName = MapPrefix + MapName;
70 // Max size of the file mapping object.
71 internal const uint MapSize = 65536;
73 // File offset where the view is to begin.
74 internal const uint ViewOffset = 0;
76 // The number of bytes of a file mapping to map to the view. All bytes of
77 // the view must be within the maximum size of the file mapping object
78 // (MAP_SIZE). If VIEW_SIZE is 0, the mapping extends from the offset
79 // (VIEW_OFFSET) to the end of the file mapping.
80 internal const uint ViewSize = 1024;
82 // Unicode string message to be written to the mapped view. Its size in
83 // byte must be less than the view size (VIEW_SIZE).
84 internal const string Message = "Message from the first process.";
87 static void Main(string[] args)
89 SafeFileMappingHandle hMapFile = null;
90 IntPtr pView = IntPtr.Zero;
92 try
94 // Create the file mapping object.
95 hMapFile = NativeMethod.CreateFileMapping(
96 INVALID_HANDLE_VALUE, // Use paging file - shared memory
97 IntPtr.Zero, // Default security attributes
98 FileProtection.PAGE_READWRITE, // Allow read and write access
99 0, // High-order DWORD of file mapping max size
100 MapSize, // Low-order DWORD of file mapping max size
101 FullMapName // Name of the file mapping object
104 if (hMapFile.IsInvalid)
106 throw new Win32Exception();
109 Console.WriteLine("The file mapping ({0}) is created", FullMapName);
111 // Map a view of the file mapping into the address space of the
112 // current process.
113 pView = NativeMethod.MapViewOfFile(
114 hMapFile, // Handle of the map object
115 FileMapAccess.FILE_MAP_ALL_ACCESS, // Read and write access
116 0, // High-order DWORD of file offset
117 ViewOffset, // Low-order DWORD of file offset
118 ViewSize // Byte# to map to the view
121 if (pView == IntPtr.Zero)
123 throw new Win32Exception();
126 Console.WriteLine("The file view is mapped");
128 // Prepare a message to be written to the view. Append '\0' to
129 // mark the end of the string when it is marshaled to the native
130 // memory.
131 byte[] bMessage = Encoding.Unicode.GetBytes(Message + '\0');
133 // Write the message to the view.
134 Marshal.Copy(bMessage, 0, pView, bMessage.Length);
136 Console.WriteLine("This message is written to the view:\n\"{0}\"",
137 Message);
139 // Wait to clean up resources and stop the process.
140 Console.Write("Press ENTER to clean up resources and quit");
141 Console.ReadLine();
143 catch (Exception ex)
145 Console.WriteLine("The process throws the error: {0}", ex.Message);
147 finally
149 if (hMapFile != null)
151 if (pView != IntPtr.Zero)
153 // Unmap the file view.
154 NativeMethod.UnmapViewOfFile(pView);
155 pView = IntPtr.Zero;
157 // Close the file mapping object.
158 hMapFile.Close();
159 hMapFile = null;
165 #region Native API Signatures and Types
167 /// <summary>
168 /// Memory Protection Constants
169 /// http://msdn.microsoft.com/en-us/library/aa366786.aspx
170 /// </summary>
171 [Flags]
172 public enum FileProtection : uint
174 PAGE_NOACCESS = 0x01,
175 PAGE_READONLY = 0x02,
176 PAGE_READWRITE = 0x04,
177 PAGE_WRITECOPY = 0x08,
178 PAGE_EXECUTE = 0x10,
179 PAGE_EXECUTE_READ = 0x20,
180 PAGE_EXECUTE_READWRITE = 0x40,
181 PAGE_EXECUTE_WRITECOPY = 0x80,
182 PAGE_GUARD = 0x100,
183 PAGE_NOCACHE = 0x200,
184 PAGE_WRITECOMBINE = 0x400,
185 SEC_FILE = 0x800000,
186 SEC_IMAGE = 0x1000000,
187 SEC_RESERVE = 0x4000000,
188 SEC_COMMIT = 0x8000000,
189 SEC_NOCACHE = 0x10000000
193 /// <summary>
194 /// Access rights for file mapping objects
195 /// http://msdn.microsoft.com/en-us/library/aa366559.aspx
196 /// </summary>
197 [Flags]
198 public enum FileMapAccess
200 FILE_MAP_COPY = 0x0001,
201 FILE_MAP_WRITE = 0x0002,
202 FILE_MAP_READ = 0x0004,
203 FILE_MAP_ALL_ACCESS = 0x000F001F
207 /// <summary>
208 /// Represents a wrapper class for a file mapping handle.
209 /// </summary>
210 [SuppressUnmanagedCodeSecurity,
211 HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
212 internal sealed class SafeFileMappingHandle : SafeHandleZeroOrMinusOneIsInvalid
214 [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
215 private SafeFileMappingHandle()
216 : base(true)
220 [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
221 public SafeFileMappingHandle(IntPtr handle, bool ownsHandle)
222 : base(ownsHandle)
224 base.SetHandle(handle);
227 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success),
228 DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
229 [return: MarshalAs(UnmanagedType.Bool)]
230 private static extern bool CloseHandle(IntPtr handle);
232 protected override bool ReleaseHandle()
234 return CloseHandle(base.handle);
239 internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
242 /// <summary>
243 /// The class exposes Windows APIs used in this code sample.
244 /// </summary>
245 [SuppressUnmanagedCodeSecurity]
246 internal class NativeMethod
248 /// <summary>
249 /// Creates or opens a named or unnamed file mapping object for a
250 /// specified file.
251 /// </summary>
252 /// <param name="hFile">
253 /// A handle to the file from which to create a file mapping object.
254 /// </param>
255 /// <param name="lpAttributes">
256 /// A pointer to a SECURITY_ATTRIBUTES structure that determines
257 /// whether a returned handle can be inherited by child processes.
258 /// </param>
259 /// <param name="flProtect">
260 /// Specifies the page protection of the file mapping object. All
261 /// mapped views of the object must be compatible with this
262 /// protection.
263 /// </param>
264 /// <param name="dwMaximumSizeHigh">
265 /// The high-order DWORD of the maximum size of the file mapping
266 /// object.
267 /// </param>
268 /// <param name="dwMaximumSizeLow">
269 /// The low-order DWORD of the maximum size of the file mapping
270 /// object.
271 /// </param>
272 /// <param name="lpName">
273 /// The name of the file mapping object.
274 /// </param>
275 /// <returns>
276 /// If the function succeeds, the return value is a handle to the
277 /// newly created file mapping object.
278 /// </returns>
279 [DllImport("Kernel32.dll", SetLastError = true)]
280 public static extern SafeFileMappingHandle CreateFileMapping(
281 IntPtr hFile,
282 IntPtr lpAttributes,
283 FileProtection flProtect,
284 uint dwMaximumSizeHigh,
285 uint dwMaximumSizeLow,
286 string lpName);
289 /// <summary>
290 /// Maps a view of a file mapping into the address space of a calling
291 /// process.
292 /// </summary>
293 /// <param name="hFileMappingObject">
294 /// A handle to a file mapping object. The CreateFileMapping and
295 /// OpenFileMapping functions return this handle.
296 /// </param>
297 /// <param name="dwDesiredAccess">
298 /// The type of access to a file mapping object, which determines the
299 /// protection of the pages.
300 /// </param>
301 /// <param name="dwFileOffsetHigh">
302 /// A high-order DWORD of the file offset where the view begins.
303 /// </param>
304 /// <param name="dwFileOffsetLow">
305 /// A low-order DWORD of the file offset where the view is to begin.
306 /// </param>
307 /// <param name="dwNumberOfBytesToMap">
308 /// The number of bytes of a file mapping to map to the view. All bytes
309 /// must be within the maximum size specified by CreateFileMapping.
310 /// </param>
311 /// <returns>
312 /// If the function succeeds, the return value is the starting address
313 /// of the mapped view.
314 /// </returns>
315 [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
316 public static extern IntPtr MapViewOfFile(
317 SafeFileMappingHandle hFileMappingObject,
318 FileMapAccess dwDesiredAccess,
319 uint dwFileOffsetHigh,
320 uint dwFileOffsetLow,
321 uint dwNumberOfBytesToMap);
324 /// <summary>
325 /// Unmaps a mapped view of a file from the calling process's address
326 /// space.
327 /// </summary>
328 /// <param name="lpBaseAddress">
329 /// A pointer to the base address of the mapped view of a file that
330 /// is to be unmapped.
331 /// </param>
332 /// <returns></returns>
333 [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
334 [return: MarshalAs(UnmanagedType.Bool)]
335 public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
338 #endregion